<template>
  <div class="app-container managePointsDialog" v-if="user">
    <el-dialog :title="textMap[dialogStatus]" :visible="true" :close-on-click-modal="false" @close="$emit('close')">
      <div class="filter-container">
        <div>
          <el-input type="number" placeholder="-50, 50" v-model="changeAmount"></el-input>
          <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit"
            @click="handleUpdate">
            {{ $t('table.edit') }}
          </el-button>
        </div>
        <div>
          <el-select v-model="listQuery.sort" style="width: 140px" class="filter-item" @change="handleFilter">
            <el-option v-for="item in sortOptions" :key="item.key" :label="item.label" :value="item.key" />
          </el-select>
          <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download"
            @click="handleDownload">
            {{ $t('table.export') }}
          </el-button>
        </div>
      </div>

      <el-table :key="tableKey" v-loading="listLoading" :data="list" border fit highlight-current-row style="width: 100%;"
        @sort-change="sortChange">
        <el-table-column :label="$t('table.id')" prop="id" sortable="custom" align="center" width="80"
          :class-name="getSortClass('id')">
          <template slot-scope="{row}">
            <span>{{ row.id }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('table.date')" width="150px" align="center">
          <template slot-scope="{row}">
            <span>{{ row.created_at | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('table.changeAmount')" width="110px" align="center">
          <template slot-scope="{row}">
            <span>
              {{row.changeAmount}}
            </span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('table.reason')" min-width="150px">
          <template slot-scope="{row}">
            <span>{{ $t('table.'+row.reason) }}</span>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
        @pagination="getList" />
    </el-dialog>
  </div>
</template>

<script>
import { getPointsHistoryListByPage, updatePoints } from '@/api/points'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import i18n from '@/lang'

const calendarTypeOptions = [
  { key: 'enabled', display_name: i18n.t('table.enabled') },
  { key: 'disabled', display_name: i18n.t('table.disabled') }
]

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'ComplexTable',
  props: ['user'],
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        type: undefined,
        sort: 'DESC',
        userId: undefined,
      },
      calendarTypeOptions,
      sortOptions: [{ label: '最新', key: 'DESC' }, { label: '最旧', key: 'ASC' }],
      temp: {
        id: undefined,
        username: '',
        password: '',
        status: 'enabled',
        avatarFileId: undefined
      },
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        status: [{ required: true, message: 'type is required', trigger: 'change' }],
        username: [{ required: true, message: 'username is required', trigger: 'blur' }],
        password: [{ required: true, message: 'password is required', trigger: 'blur' }],
        avatarFileId: [{ required: true, message: 'image is required', trigger: 'blur' }]
      },
      downloadLoading: false,
      file: null,
      editPassword: false,
      changeAmount: undefined
    }
  },
  watch: {
    user(val){
      if(val){
        this.getList()
      }
    }
  },
  methods: {
    getList() {
      if(!this.user?.id)return
      this.listLoading = true
      this.listQuery.userId = this.user.id
      getPointsHistoryListByPage(this.listQuery).then(res => {
        console.log(res.data, 'res')
        this.list = res.data.rows
        this.listLoading = false
        this.total = res.data.total
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = 'DESC'
      } else {
        this.listQuery.sort = 'ASC'
      }
      this.handleFilter()
    },
    handleUpdate() {
      updatePoints({
        userId: this.user.id,
        changeAmount: Number(this.changeAmount)
      }).then(res => {
        this._visible = false
        this.$notify({
          title: '成功',
          message: '更新成功',
          type: 'success',
          duration: 2000
        })
        this.getList()
        this.$emit('refresh')
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'status']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function (key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    },
    onUploadSuccess(e) {
      if (e?.code === 200) {
        this.$message.success(e.msg)
        this.file = e.data
        this.temp.avatarFileId = e.data.id
      } else {
        this.$message.error(e.msg)
      }
    },
    onUploadError(e) {
      this.$message.error(e.msg || 'faild')
    }
  }
}
</script>

<style lang="scss">
.managePointsDialog {
  .filter-container {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;

    .el-input {
      max-width: 200px;
    }

    div {
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      gap: 5px;
      flex: 1;

      .el-button,
      .el-select {
        margin: 0 !important;
      }
    }
  }
}
</style>
